package de.tabuma.shopping.view;

import de.tabuma.lib.*;
import de.tabuma.shopping.*;
import de.tabuma.shopping.entity.*;
import java.io.*;
import java.lang.reflect.*;
import java.text.*;
import java.util.*;
import java.util.logging.*;
import javax.servlet.*;
import javax.servlet.http.*;

/**
 *
 * @author alefen
 */
public class licenseassignmenttable extends tabumaview {

    private static final Logger log = Logger.getLogger(licenseassignmenttable.class.getName());

    String orderNav;
    public licenseassignmenttable(String servlet, Hashtable parameter, String orderNav) {
        super(servlet, parameter);
        this.orderNav = orderNav;
    }

    @Override
    public void processRequest(ServletContext context, HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
        out.println("<p class=\"contentContentHeader\">License Types</p>");
        out.println("<table class=\"contenttable\">");
        out.println("<tr>");
        out.println("<th class=\"contentth\">LicenseTyp</th>");
        out.println("<th class=\"contentth\">Assigned License</th>");
        out.println("<th class=\"contentth\">Used License</th>");
        out.println("</tr>");

        List<LicensePackage> lpList = (List<LicensePackage>) request.getAttribute(constants.ORDER_ALL_LICENSEPACKAGE_LIST);
        List<LicenseType> myList = (List<LicenseType>) request.getAttribute(constants.ORDER_LICENSE_TYPE_LIST);
        Hashtable<Integer,Integer> assignedLicense = (Hashtable<Integer,Integer>) request.getAttribute(constants.ORDER_LICENSE_ASSIGNED_LICENSE);
        Hashtable<Integer,Integer> usedLicense = (Hashtable<Integer,Integer>) request.getAttribute(constants.ORDER_LICENSE_USED_LICENSE);
        Hashtable<String,Integer> freeLicenes = (Hashtable<String,Integer>) request.getAttribute(constants.ORDER_LICENSE_ASSIGNMENT_UNUSED_LICENSES_HASH);
        String orderLicenseTypeNr = (String) request.getAttribute(constants.ORDER_LICENSE_TYPE_NR);
        int orderLicenseTypeNrInt = 0;
        if(orderLicenseTypeNr!=null) {
            orderLicenseTypeNrInt = Integer.valueOf(orderLicenseTypeNr);
        }
        for(int i=0;i<myList.size();i++) {
            LicenseType licenseType = myList.get(i);
            Integer count = assignedLicense.get(licenseType.getId());
            Integer used = usedLicense.get(licenseType.getId());
            out.println("<tr>");
            if(licenseType.getId()==orderLicenseTypeNrInt) {
                List<LicenseAssignment> list = (List<LicenseAssignment>) request.getAttribute(constants.ORDER_LICENSE_ASSIGNMENT_LIST);
                List<Order> orderList = (List<Order>) request.getAttribute(constants.ORDER_LIST);
                List assignmentObjectList = (List) request.getAttribute(constants.ORDER_LICENSE_ASSIGNMENT_OBJECT_LIST);
                Class assignmentClass = (Class) request.getAttribute(constants.ORDER_LICENSE_ASSIGNMENT_CLASS);
                Field assignmentKey = (Field) request.getAttribute(constants.ORDER_LICENSE_ASSIGNMENT_FIELD_KEY);
                Field assignmentShow = (Field) request.getAttribute(constants.ORDER_LICENSE_ASSIGNMENT_FIELD_SHOW);
                String assignmentObjectname = (String) request.getAttribute(constants.ORDER_LICENSE_ASSIGNMENT_OBJECTNAME);
                List<OrderLicensePackageRelation> olprList = (List<OrderLicensePackageRelation>) request.getAttribute(constants.ORDER_LICENSE_RELATION_LIST);
                String licenseAssignmentId = (String) request.getAttribute(constants.ORDER_LICENSE_ASSIGNMENT_ID);
                if(licenseAssignmentId==null) {
                    licenseAssignmentId = "0";
                }
                int licenseAssignmentIdInt = Integer.valueOf(licenseAssignmentId);
                
                out.println("<td class=\"contenttd\"><a href=\""+this.getServlet()+"?"+orderNav+"="+constants.ORDERNAV_NULL+"&amp;"+this.getLinkAsAttribute()+"\"><img src=\"grafiken/minus1.png\" name=\"plusimage\" border=\"0\" alt=\"Plus Image\" /> " + licenseType.getName() + "</a></td>");
                out.println("<td class=\"contenttdright\">" + count + "</td>");
                out.println("<td class=\"contenttdright\">" + used + "</td>");
                out.println("</tr>");
                out.println("<tr>");
                out.println("<td class=\"contenttd\" colspan=\"3\">");
                out.println("<table class=\"contenttable\">");
                out.println("<tr>");
                out.println("<th class=\"contentth\">Assigned License from Order</th>");
                out.println("<th class=\"contentth\">Count</th>");
                out.println("<th class=\"contentth\">Used</th>");
                out.println("<th class=\"contentth\">Assigned to</th>");
                out.println("<th class=\"contentth\"></th>");
                out.println("</tr>");
                for(int j=0;j<list.size();j++) {
                    LicenseAssignment la = list.get(j);
                    String orderName = "";
                    for(int k=0;k<olprList.size();k++) {
                        OrderLicensePackageRelation olpr = olprList.get(k);
                        if(olpr.getId().intValue()==la.getOrderLicensePackageRelationId()) {
                            for(int l=0;l<orderList.size();l++) {
                                Order order = orderList.get(l);
                                if(order.getId().intValue()==olpr.getOrderId()) {
                                    DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
                                    orderName = "order "+df.format(order.getOrderDate());
                                }
                            }
                        }
                    }
                    out.println("<tr>");
                    out.println("<td class=\"contenttdright\">"+orderName+"</td>");
                    out.println("<td class=\"contenttdright\">"+la.getLicenseCount()+"</td>");
                    if(la.getId().intValue()==licenseAssignmentIdInt) {
                        out.println("<td class=\"contenttdright\"><a href=\""+this.getServlet()+"?"+constants.ORDER_LICENSE_TYPE_NR+"="+licenseType.getId()+"&amp;"+orderNav+"="+constants.ORDERNAV_NULL+"&amp;"+this.getLinkAsAttribute()+"\"><img src=\"grafiken/minus1.png\" name=\"minusimage\" border=\"0\" alt=\"Minus Image\" /> "+la.getLicenseUsed()+"</a></td>");
                    }
                    else {
                        out.println("<td class=\"contenttdright\"><a href=\""+this.getServlet()+"?"+this.getLinkAsAttribute()+"&amp;"+constants.ORDER_LICENSE_TYPE_NR+"="+orderLicenseTypeNrInt+"&amp;"+constants.ORDER_LICENSE_ASSIGNMENT_ID+"="+la.getId().intValue()+"\"><img src=\"grafiken/plus1.png\" name=\"plusimage\" border=\"0\" alt=\"Plus Image\" /> "+la.getLicenseUsed()+"</a></td>");
                    }
                    String assignedName = "";
                    for(int k=0;k<assignmentObjectList.size();k++) {
                        try {
                            Object oject = assignmentObjectList.get(k);
                            String getMethodId = ObjectMethods.getGetter(assignmentKey.getName());
                            Long id = (Long) assignmentClass.getMethod(getMethodId).invoke(oject);
                            String getMethodShow = ObjectMethods.getGetter(assignmentShow.getName());
                            String nameOfAssignment = (String) assignmentClass.getMethod(getMethodShow).invoke(oject);
                            if(id.intValue()==la.getAssignmentId()) {
                                assignedName = nameOfAssignment;
                            }
                        }
                        catch(Exception e) {
                            String warning = e.getMessage()+"/"+e.getCause()+"/"+e.getClass()+"\n";
                            for(int l=0;l<e.getStackTrace().length;l++) {
                                warning += e.getStackTrace()[l]+"\n";
                            }
                            log.warning(warning);
                        }
                    }
                    out.println("<td class=\"contenttdright\">"+assignedName+"</td>");
                    if(la.getLicenseCount()>la.getLicenseUsed()) {
                        out.println("<td class=\"contenttdright\"><a href=\""+this.getServlet()+"?"+this.getLinkAsAttribute()+"&amp;"+constants.ORDER_LICENSE_TYPE_NR+"="+licenseType.getId()+"&amp;"+constants.ORDER_LICENSE_ASSIGNMENT_ID+"="+la.getId().intValue()+"&amp;"+constants.ORDER_LICENSE_ASSIGNMENT_REMOVE+"=true\">remove remaining licenses</a></td>");
                    }
                    else {
                        out.println("<td class=\"contenttdright\">not removable</td>");
                    }
                    out.println("</tr>");
                    if(la.getId().intValue()==licenseAssignmentIdInt) {
                        Hashtable<Integer,String> methodList = (Hashtable<Integer,String>) request.getAttribute(constants.ORDER_LICENSE_ASSIGNMENT_METHOD_LIST);
                        List<LicenseUse> luList = (List<LicenseUse>) request.getAttribute(constants.ORDER_LICENSE_ASSIGNMENT_USED_LICENSES_LIST);
                        out.println("<tr>");
                        out.println("<td colspan=\"5\">");
                        out.println("<table class=\"contenttable\">");
                        out.println("<tr>");
                        out.println("<th class=\"contentth\">Method</th>");
                        out.println("<th class=\"contentth\">Date</th>");
                        out.println("<th class=\"contentth\">Usage Informationen</th>");
                        out.println("</tr>");
                        for(int l=0;l<luList.size();l++) {
                            LicenseUse lu = luList.get(l);
                            out.println("<tr>");
                            out.println("<td class=\"contenttdright\">"+methodList.get(lu.getMethodId())+"</td>");
                            DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
                            out.println("<td class=\"contenttdright\">"+df.format(lu.getDate())+"</td>");
                            out.println("<td class=\"contenttdright\">"+lu.getUseInformation()+"</td>");
                            out.println("</tr>");
                        }
                        if(luList.size()==0) {
                            out.println("<tr>");
                            out.println("<td class=\"contenttdright\" colspan=\"3\">no entry</td>");
                            out.println("</tr>");
                        }
                        out.println("</table>");
                        out.println("</td>");
                        out.println("</tr>");
                    }
                }

                if(list.size()==0) {
                    out.println("<tr><td colspan=\"3\" class=\"contenttd\">no content</td></tr>");
                }
                out.println("</table>");
                out.println("<br/>");
                out.println("<div class=\"contentBoxed\">");
                out.println("<div class=\"contentHeader\">Add Assignment</div>");
                out.println("<div class=\"contentContent\">");
                out.println(this.getFormBeginn(null));
                out.println(this.getHiddenAsAttribute());
                out.println(view.printHiddenField(constants.ORDER_LICENSE_TYPE_NR, orderLicenseTypeNr));
                out.println(view.printHiddenField(constants.ORDER_LICENSE_ASSIGNMENT_ADD, "true"));

                String select = "<select name=\""+constants.ORDER_LICENSE_ASSIGNMENT_ID+"\">";
                for(int j=0;j<assignmentObjectList.size();j++) {
                    try {
                        Object oject = assignmentObjectList.get(j);
                        String getMethodId = ObjectMethods.getGetter(assignmentKey.getName());
                        Long id = (Long) assignmentClass.getMethod(getMethodId).invoke(oject);
                        String getMethodShow = ObjectMethods.getGetter(assignmentShow.getName());
                        String groupName = (String) assignmentClass.getMethod(getMethodShow).invoke(oject);
                        select += "<option value=\""+id.intValue()+"\">"+assignmentObjectname+" "+groupName+"</option>";
                    }
                    catch(Exception e) {
                        String warning = e.getMessage()+"/"+e.getCause()+"/"+e.getClass()+"\n";
                        for(int k=0;k<e.getStackTrace().length;k++) {
                            warning += e.getStackTrace()[k]+"\n";
                        }
                        log.warning(warning);
                    }
                }
                select += "</select>";
                out.println("<div class=\"cols\">");
                out.println("<div class=\"col1\">");
                out.println("<div class=\"col1_head\">Assigned To</div>");
                out.println("<div class=\"col1_content\">"+select+"</div>");
                out.println("</div>");
                String orderName = "Order / License";

                out.println("<div class=\"col1\">");
                out.println("<div class=\"col1_head\">"+orderName+"</div>");
                out.println("<div class=\"col1_content\"><select name=\""+constants.ORDER_LICENSE_ASSIGNMENT_ADD_ID+"\">");

                List<OrderLicensePackageRelation> payedOlprList = getPayedOrderLicensePackageRelation(olprList, orderList);
                for(int j=0;j<payedOlprList.size();j++) {
                    OrderLicensePackageRelation olpr = payedOlprList.get(j);
                    Date date = getDateOfOrder(olpr.getOrderId(), orderList);

                    DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
                    String orderDescription = "order ";
                    if(date!=null) {
                        orderDescription += df.format(date);
                    }
                    LicensePackage lp = getLicensePackage(olpr.getLicensePackageId(), lpList);
                    if(lp!=null) {
                        String licensePackageName = lp.getName();
                        for(int k=0;k<lp.getList().length;k++) {
                            License license = lp.getList()[k];
                            if(license.getLicenseTyp()==licenseType.getId()) {
                                String key = olpr.getId().intValue()+"_"+k;
                                Integer freeLicenseCount = freeLicenes.get(key);
                                out.println("<option value=\""+olpr.getId()+"_"+license.getId()+"_"+k+"\">"+orderDescription+" "+licensePackageName+" "+licenseType.getName()+" ("+freeLicenseCount+" licences free)</option>");
                            }
                        }
                    }
                }
                out.println("</select>");
                out.println("</div>");
                out.println("</div>");

                out.println(view.printForm1("Count License",constants.ORDER_LICENSE_ASSIGNMENT_COUNT, null));

                out.println("</div>");
                out.println("<input type=\"submit\" class=\"button\" name=\"\" value=\"Value\"/>");
                out.println(this.getFormEnd());
                out.println("</div>");
                out.println("</div>");
                out.println("</td>");
            }
            else {
                out.println("<td class=\"contenttd\"><a href=\""+this.getServlet()+"?"+constants.ORDER_LICENSE_TYPE_NR+"="+licenseType.getId()+"&amp;"+orderNav+"="+constants.ORDERNAV_NULL+"&amp;"+this.getLinkAsAttribute()+"\"><img src=\"grafiken/plus1.png\" name=\"plusimage\" border=\"0\" alt=\"Plus Image\" /> " + licenseType.getName() + "</a></td>");
                out.println("<td class=\"contenttdright\">" + count + "</td>");
                out.println("<td class=\"contenttdright\">" + used + "</td>");
            }
            
            out.println("</tr>");
        }
        out.println("</table>");
        out.println("<br/>");
    }
    
    public static List<OrderLicensePackageRelation> getPayedOrderLicensePackageRelation(List<OrderLicensePackageRelation> olpr, List<Order> oList) {
        List<OrderLicensePackageRelation> olprList = new ArrayList<OrderLicensePackageRelation>();
        for(int i=0;i<olpr.size();i++) {
            OrderLicensePackageRelation olprElement = olpr.get(i);
            for(int j=0;j<oList.size();j++) {
                Order order = oList.get(j);
                if(order.getId().intValue()==olprElement.getOrderId() && order.getPayed()) {
                    olprList.add(olprElement);
                }
            }
        }
        return olprList;
    }

    public static LicensePackage getLicensePackage(int id, List<LicensePackage> lpList) {
        for(int i=0;i<lpList.size();i++) {
            if(lpList.get(i).getId().intValue()==id) {
                return lpList.get(i);
            }
        }
        return null;
    }

    public static License getLicense(int licenseType, License[] license) {
        for(int i=0;i<license.length;i++) {
            if(license[i].getLicenseTyp()==licenseType) {
                return license[i];
            }
        }
        return null;
    }

    public static Date getDateOfOrder(int id, List<Order> oList) {
        for(int i=0;i<oList.size();i++) {
            if(oList.get(i).getId().intValue()==id) {
                return oList.get(i).getOrderDate();
            }
        }
        return null;
    }
}
